//
//  MapViewVC.swift
//  ShareUmbrella
//
//  Created by niupark on 2017/9/13.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import SWRevealViewController
import RxSwift
import CoreLocation
import TSMessages
import SwiftyJSON

enum UserType {
    case none
    case allUser //所有用户
    case askForHelper //请求帮助者
    case acceptHelper //提供帮助者
    case connnetedUser //建立关系的用户
}

class MyMaPointAnnotation: MAPointAnnotation {
    public var data:JSON?
    public var isExist: Bool = false
}

class MapViewVC: YSBaseViewController {

    let RoutePlanningPaddingEdge = CGFloat(20)
    let RoutePlanningViewControllerStartTitle = "起点"
    let RoutePlanningViewControllerDestinationTitle = "终点"
    var showStartAndEnd = false //是否显示起点和终点

    var pointAnnotaction:[MyMaPointAnnotation] = []
    var mapView: MAMapView!
    var searchAPI: AMapSearchAPI!
    var naviRoute: MANaviRoute? //用于显示当前路线方案.
    var startAnnotation: MAPointAnnotation?
    var destinationAnnotation: MAPointAnnotation?
    var route: AMapRoute!           //路径规划信息
    var startCoordinate: CLLocationCoordinate2D? //起始点经纬度
    var destinationCoordinate: CLLocationCoordinate2D? //终点经纬度
    var _locationAnnotationView:LocationAnnotationView!
    var isShowMapLine = false //是否已经显示了路线
    private var status: StatusInfo?
    public var nearbyUserType:UserType = .none  {
        didSet{
            guard oldValue != nearbyUserType  else{
                return
            }
            self.bag = DisposeBag()
            self.observerNearByUser(type: nearbyUserType)
        }
    }
    private var bag = DisposeBag()
    override func setup() {
        super.setup()
        self.searchAPI = AMapSearchAPI()
        self.searchAPI.delegate = self

    }
    /*
     *
     * 界面布局初始化
     */
    override func buildUI() {
        super.buildUI()
        mapView = MAMapView(frame: self.view.bounds).ys.customize { (view) in
            self.view.addSubview(view)
            view.delegate = self
            
            ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
//            view.showsUserLocation = true
            view.customizeUserLocationAccuracyCircleRepresentation = true
            view.allowsBackgroundLocationUpdates = true
            view.userTrackingMode = .follow

            view.setZoomLevel(14, animated: true)
        }
        

    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }

    //显示周边用户
    private func observerNearByUser(type: UserType) {
        switch type {
        case .allUser:
            Umbrella.nearbyUsers.asObservable().subscribe(onNext: { [weak self] (data) in
                guard let `self` = self , let `data` = data  else {
                    return
                }
                //更新周围人
                self.updateNearby(data: data)
                
            }).addDisposableTo(self.bag)
            
        case .acceptHelper:
            Umbrella.nearbyAcceptHelpers.asObservable().subscribe(onNext: { [weak self] (data) in
                guard let `self` = self , let `data` = data  else {
                    return
                }
                //更新周围人
                self.updateNearby(data: data)
                
            }).addDisposableTo(self.bag)
        case .askForHelper:
            Umbrella.nearbyAskForHelpers.asObservable().subscribe(onNext: { [weak self] (data) in
                guard let `self` = self , let `data` = data  else {
                    return
                }
                //更新周围人
                self.updateNearby(data: data)
                
            }).addDisposableTo(self.bag)
        case .connnetedUser:
            Umbrella.currentAskForHelper.asObservable().subscribe(onNext: { [weak self] (data) in
                guard let `self` = self , let `data1` = Umbrella.currentAskForHelper.value , let `data2` = Umbrella.currentAccepHelper.value else {
                    return
                }
                //帮助者和求助者
                self.updateNearby(data: JSON([data1, data2]))
                
            }).addDisposableTo(self.bag)
        default:
            break
        }
        
    }
    
    override func buildRx() {
        super.buildRx()
        
        _ = User.statusInfo.asObservable().takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (statusInfo) in
            guard let `self` = self , let statusInfo = statusInfo  else {
                return
            }
            guard let `status` =  self.status else {
                self.handleStatusChange(statusInfo: statusInfo)
                return
            }
            if status.status != statusInfo.status {
                self.handleStatusChange(statusInfo: statusInfo)
            }
        })
    }
    
    func handleStatusChange(statusInfo: StatusInfo) {
        
    }
    
    

}
//地图相关操作方法
extension MapViewVC {
    
    private  func findPointAnnotaction(_ userId: String) -> MyMaPointAnnotation? {
        for point in self.pointAnnotaction {
            if point.data?["userId"].stringValue == userId {
                return point
            }
        }
        return nil
    }

    func updateNearby(data:JSON) {
        var list: [MyMaPointAnnotation] = []
        
        //增量更新附近的用户
        for json in data.arrayValue {
            var point:MyMaPointAnnotation!
            if let p = self.findPointAnnotaction(json["userId"].stringValue) {
                point = p
                p.isExist = true
            }else{
                point = MyMaPointAnnotation()
                self.mapView.addAnnotation(point)
            }
            point.coordinate = CLLocationCoordinate2D(latitude: json["latitude"].doubleValue, longitude: json["longitude"].doubleValue)
            point.title = json["userNickName"].string ?? json["Tel"].string
            point.subtitle = "助人\(json["helpTiems"].intValue)次,受助\(json["RecipientTimes"].intValue)次"
            point.data = json
            list.append(point)
        }
        //删除不存在用户信息
        for point in self.pointAnnotaction {
            if !point.isExist {
                self.mapView.removeAnnotation(point)
            }else{
                point.isExist = false
            }
        }
        self.pointAnnotaction = list
        
        
    }
    //在地图上添加起始和终点的标注点
    private  func addStartAndEndAnnotations(start:CLLocationCoordinate2D, end: CLLocationCoordinate2D) {
       
        let startAnnotation = MAPointAnnotation()
        startAnnotation.coordinate = start
        startAnnotation.title = RoutePlanningViewControllerStartTitle
        startAnnotation.subtitle = "{\(start.latitude), \(start.longitude)}"
        self.startAnnotation = startAnnotation
        let destinationAnnotation = MAPointAnnotation()
        destinationAnnotation.coordinate = end
        destinationAnnotation.title = RoutePlanningViewControllerDestinationTitle
        destinationAnnotation.subtitle = "{\(end.latitude), \(end.longitude)}"
        self.destinationAnnotation = destinationAnnotation
        self.mapView.addAnnotation(startAnnotation)
        self.mapView.addAnnotation(destinationAnnotation)
    }
    
    //搜索路线
    func searchRoute(startCoordinate: CLLocationCoordinate2D, destinationCoordinate:CLLocationCoordinate2D, showStartEnd: Bool = true){
        self.startCoordinate = startCoordinate
        self.destinationCoordinate = destinationCoordinate
        self.showStartAndEnd = showStartEnd //是否显示起点和终点
        let request = AMapWalkingRouteSearchRequest()
        request.origin = AMapGeoPoint.location(withLatitude: CGFloat(startCoordinate.latitude), longitude: CGFloat(startCoordinate.longitude))
        request.destination = AMapGeoPoint.location(withLatitude: CGFloat(destinationCoordinate.latitude), longitude: CGFloat(destinationCoordinate.longitude))
        self.searchAPI?.aMapWalkingRouteSearch(request)

    }
    
    //删除路线
    
    func removeRoute() {
        if let s = self.startAnnotation, let e = self.destinationAnnotation {
            self.mapView.removeAnnotation(s)
            self.mapView.removeAnnotation(e)
        }
        self.naviRoute?.removeFromMapView() //清空地图上已有的路线
        self.isShowMapLine = false
    }
    
    //绘制路线
    func drawRoute(startPoint: AMapGeoPoint, endPoint:AMapGeoPoint, path: AMapPath, _ type: MANaviAnnotationType = .walking){
        //如果存在起点和终点，则删除
        if let s = self.startAnnotation, let e = self.destinationAnnotation {
            self.mapView.removeAnnotation(s)
            self.mapView.removeAnnotation(e)
        }
        if self.showStartAndEnd {
            //是否显示起点和终点
            self.addStartAndEndAnnotations(start: CLLocationCoordinate2D(latitude: CLLocationDegrees(startPoint.latitude), longitude: CLLocationDegrees(startPoint.longitude)), end: CLLocationCoordinate2D(latitude: CLLocationDegrees(endPoint.latitude), longitude: CLLocationDegrees(endPoint.longitude)))

        }
        
        
        //根据已经规划的路径，起点，终点，规划类型，是否显示实时路况，生成显示方案
        self.naviRoute?.removeFromMapView() //清空地图上已有的路线
        
        //根据已经规划的路径，起点，终点，规划类型，是否显示实时路况，生成显示方案
        self.naviRoute = MANaviRoute(for: self.route.paths[0], withNaviType: type, showTraffic: false, start: startPoint, end: endPoint)
        self.naviRoute?.add(to: self.mapView)
        //显示到地图上
        let edgePaddingRect = UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge)
        //第一次显示地图的时候，缩放地图使其适应polylines的展示
        if !self.isShowMapLine {
            self.mapView.setVisibleMapRect(CommonUtility.mapRect(forOverlays: self.naviRoute?.routePolylines), edgePadding: edgePaddingRect, animated: true)

        }
        self.isShowMapLine = true
        
    }

}

extension MapViewVC: MAMapViewDelegate, AMapSearchDelegate{
    

    
    func aMapSearchRequest(_ request: Any!, didFailWithError error: Error!) {
        TSMessage.showNotification(withTitle: "路线规划失败，选择距离不能超过100公里", type: .warning)
    }
    
    func onRouteSearchDone(_ request: AMapRouteSearchBaseRequest!, response: AMapRouteSearchResponse?) {
        guard let r = response, r.count > 0 else {
            return
        }
        
        guard let s = self.startCoordinate, let d = self.destinationCoordinate else {
            return
        }
        print("onRouteSearchDone")
        
        self.route = r.route
        let startPoint = AMapGeoPoint.location(withLatitude: CGFloat(s.latitude), longitude: CGFloat(s.longitude)) //起点
        let endPoint = AMapGeoPoint.location(withLatitude: CGFloat(d.latitude), longitude: CGFloat(d.longitude))  //终点
        

        
        self.drawRoute(startPoint: startPoint!, endPoint: endPoint!, path: self.route.paths[0])
        
    }

    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        if !updatingLocation && _locationAnnotationView != nil {
            self._locationAnnotationView.rotateDegree = CGFloat(userLocation.heading.trueHeading) - mapView.rotationDegree
        }
    }
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        
        //位置精度圈
        if overlay.isEqual(mapView.userLocationAccuracyCircle) {
            let accuracyCircleRender:MACircleRenderer! = MACircleRenderer.init(circle: overlay as! MACircle!)
            
            accuracyCircleRender.lineWidth = 2.0
            accuracyCircleRender.strokeColor = UIColor.lightGray
            accuracyCircleRender.fillColor = UIColor.init(colorLiteralRed: 1, green: 0, blue: 0, alpha: 0.3)
            
            return accuracyCircleRender
        }

        //虚线，如需要骑行的
        if overlay.isKind(of: LineDashPolyline.self) {
            let naviPolyline: LineDashPolyline = overlay as! LineDashPolyline
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: naviPolyline.polyline)
            renderer.lineWidth = 6
            renderer.strokeColor = UIColor.red
            renderer.lineDash = true
            
            return renderer
        }
        
        //showTraffic为NO时，不需要带实时路况，路径为单一颜色，比如骑行线路目前为海蓝色
        if overlay.isKind(of: MANaviPolyline.self) {
            
            let naviPolyline: MANaviPolyline = overlay as! MANaviPolyline
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: naviPolyline.polyline)
            renderer.lineWidth = 6
            
            if naviPolyline.type == MANaviAnnotationType.walking {
                renderer.strokeColor = UIColor(0x36B678FF)
            }
            else if naviPolyline.type == MANaviAnnotationType.railway {
                renderer.strokeColor = naviRoute?.railwayColor;
            }
            else {
                renderer.strokeColor = naviRoute?.routeColor;
            }
            
            return renderer
        }
        
        //showTraffic为YES时，需要带实时路况，路径为多颜色渐变
        if overlay.isKind(of: MAMultiPolyline.self) {
            let renderer: MAMultiColoredPolylineRenderer = MAMultiColoredPolylineRenderer(multiPolyline: overlay as! MAMultiPolyline!)
            renderer.lineWidth = 6
            renderer.strokeColors = naviRoute?.multiPolylineColors
            
            return renderer
        }
        
        return nil
    }

    
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        if annotation.isKind(of: MAUserLocation.self) {
            let userLocationStyleReuseIndetifier = "userLocationStyleReuseIndetifier"
            
            var annotationView:MAAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: userLocationStyleReuseIndetifier)
            
            if annotationView == nil {
                annotationView = LocationAnnotationView(annotation: annotation, reuseIdentifier: userLocationStyleReuseIndetifier)
                annotationView.canShowCallout = true
            }
            
            _locationAnnotationView = annotationView as! LocationAnnotationView
            _locationAnnotationView.updateImage(image: UIImage(named: "userPosition"), tintColor: UIColor(0x36B678FF))
            
            return annotationView
        }
        if let myAnnotation = annotation as? MyMaPointAnnotation {
            var annotationView: CustomAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: CustomAnnotationView.className()) as? CustomAnnotationView
            
            if annotationView == nil {
                annotationView = CustomAnnotationView(annotation: myAnnotation, reuseIdentifier: CustomAnnotationView.className())
            }
            annotationView!.avatorUrlString = myAnnotation.data?["userAvator"].string
            annotationView!.canShowCallout = true
            return annotationView!
        }else if annotation.isKind(of: MAPointAnnotation.self) {
            
            //标注的view的初始化和复用
            let pointReuseIndetifier = "RoutePlanningCellIdentifier"
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
                annotationView!.canShowCallout = true
                annotationView!.isDraggable = false
            }
            
            annotationView!.image = nil
            
            if annotation.isKind(of: MANaviAnnotation.self) {
                let naviAnno = annotation as! MANaviAnnotation
                
                switch naviAnno.type {
                case MANaviAnnotationType.railway:
                    annotationView!.image = UIImage(named: "railway_station")
                    break
                case MANaviAnnotationType.drive:
                    annotationView!.image = UIImage(named: "car")
                    break
                case MANaviAnnotationType.riding:
                    annotationView!.image = UIImage(named: "ride")
                    break
                case MANaviAnnotationType.walking:
                    annotationView!.image = UIImage(named: "man")
                    break
                case MANaviAnnotationType.bus:
                    annotationView!.image = UIImage(named: "bus")
                    break
                }
            }
            else {
                if annotation.title == "起点" {
                    annotationView!.image = UIImage(named: "startPoint")
                }
                else if annotation.title == "终点" {
                    annotationView!.image = UIImage(named: "endPoint")
                }
            }
            return annotationView!
        }
        return nil
    }
}

